var utils = require('./utils');
var cheerio = require('cheerio');
var dao = require('./dao');

exports.loadRank = loadRank;

function loadRank(keyword,ep) {

    //苹果7手机壳卡通&pvid=3aa33ff3f074420286480fd0cbfae17c
    //var keyword = "苹果7手机壳卡通可爱";
    var currPage = 1;
    var key = encodeURI(keyword);
    var url = "https://search.jd.com/Search?keyword="+key+"&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&page="+currPage;
    //\w[.]\w+[(]\d+[,]\d+[,]\d+[,]["]["][,]\d+[,]\d+[,]\d+
    var url_s = "https://search.jd.com/s_new.php?keyword="+key+"&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq="+key+"&page={PAGE}&s=28&scrolling=y&pos=30&tpl=3_M&show_items=";
    //https://search.jd.com/s_new.php?keyword=%E8%8B%B9%E6%9E%9C7%E6%89%8B%E6%9C%BA%E5%A3%B3%E5%8D%A1%E9%80%9A%E5%8F%AF%E7%88%B1&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=3&wq=%E8%8B%B9%E6%9E%9C7%E6%89%8B%E6%9C%BA%E5%A3%B3%E5%8D%A1%E9%80%9A%E5%8F%AF%E7%88%B1&page=2&s=28&scrolling=y&pos=30&log_id=1488874131.24389&tpl=3_M&show_items=10672908747,10423330591,11227423038,10856788107,11403542386,10624373691,10980545877,10695614964,3823691,3179881,11244547805,10994927124,11097983694,11358391973,10653197631,10686500220,10668837058,11015804511,10984372253,10812287583,10782243705,11495978742,11332598397,10976252388,10670295943,11309117486,10649790290,10834020873,11335261051,1694916782
    var items = "";
    utils.getc(url,1,function (html) {
        var $ = cheerio.load(html);
        var index = 0;
        var params = [];
        $(".gl-item","#J_goodsList").each(function (i,e) {
            //var obj = {};
            if($(e).attr("data-type")!='activity'){//不是 活动
                var sku = $(e).attr("data-sku");
                var data = loadData($, e);
                index = i + 1;
                data.index = index;
                data.pageNum = currPage;
                data.keyword = keyword;
                data.rank = index;
                items += sku + ",";
                //console.log(obj);
                //dao.saveHotKeyRank(obj);
                params.push([data.keyword,data.rank, data.sku,data.name, data.isZy,data.pageNum,data.index,
                    data.price||0,data.commit,data.isAd,data.img,data.url]);
            }
        });
        index ++;
        url_s = url_s.replace("{PAGE}",currPage+1);
        utils.getc(url_s+items,1,function (aa) {
            var $ = cheerio.load(aa);
            $(".gl-item").each(function (i,e) {
                var data = loadData($, e);
                data.rank = index;
                data.index = index++;
                data.pageNum = currPage+1;
                data.keyword = keyword;

                //console.log(obj);
                //dao.saveHotKeyRank(obj);
                params.push([data.keyword,data.rank, data.sku,data.name, data.isZy,data.pageNum,data.index,
                    data.price||0,data.commit,data.isAd,data.img,data.url]);

            });

            var sql = "INSERT into t_jd_hot_key_ranking(fetch_time,keyword,rank,sku_id,pro_name,is_jd_zy,";
            sql += "page_num,page_set,pro_price,comment_total_number,is_extension,img_url,pro_url)";
            sql += "values(CURDATE(),?,?,?,?,?,?,?,?,?,?,?,?);";
            
            dao.execTrans(sql,params,function (err) {
                if(err) console.log(err + "");
                ep.emit("next_word",keyword);
            });
        })
    })

}
function loadData($,e) {
    var sku  = $(e).attr("data-sku");
    var spu  = $(e).attr("data-spu");
    var name = $(".p-name > a",$(e)).attr("title");
    var img = $(".p-img img", $(e)).first().attr("src");
    if(img == undefined){
        img = $(".p-img img", $(e)).first().attr("data-lazy-img");
    }
    var url = $(".p-img a",$(e)).first().attr("href");
    var commit = $(".p-commit a",$(e)).first().text().replace("+","");
    if(commit.indexOf('万')>0){
        commit = parseFloat(commit)*10000;
    }
    var shop = $("div.p-shop > span > a ", $(e)).text();

    var price = $(".p-price strong>i", $(e)).first().text();
    var isZy = $(".p-icons img", $(e)).first().attr("data-tips")=='京东自营，品质保障'?1:0;
    var isAd = $(".p-promo-flag",$(e)).is("span")?1:0;
    var  obj = {
        name: name,
        img: "https:"+img,
        sku: sku,
        //shop: shop,
        price: price,
        commit: commit,
        isZy: isZy,
        isAd: isAd?1:0,
        isActivity: 0,
        url: isAd?url:"https:"+url,
        //index: (i+1),
        //pageNum :currPage,
        //keyword:keyword,
        //psort:psort,
        //wtype:wtype
    };

    return obj;

}





function loadActivity($,e) {
    var ad_title = $(".gl-act-title",$(e)).text();
    var ad_info = $(".gl-act-infor",$(e)).text();
    var name = ad_title+"#"+ad_info;
    var img = $(".gl-act-img img",$(e)).attr("src");
    if(img == undefined){
        img = $(".gl-act-img img", $(e)).attr("data-lazy-img");
    }
    var url = $(".gl-act-img a",$(e)).attr("href");
    var obj = {
        name: name,
        img: img,
        //shop: '',
        sku: '',
        price: 0,
        commit: 0,
        isZy: 0,
        isAd: 1,
        isActivity: 1,
        url: url,
        index: (i+1),
        pageNum :currPage,
        keyword:keyword,
        //psort:psort,
        //wtype:wtype
    };
}

var page = function(F,current_page) {
    var shop_count = 0,promotion_count =0;
    F = parseInt(F, 10);
    if (F < 1) {
        F = 1
    }
    var H, E = Math.min,
        B = 1,
        D =  30 * B,
        G = 1 * B,
        A = 2 * B;
    if (F == 1) {
        H = 1
    } else {
        if (F < this.current_page) {
            H = this.prev_start - (this.current_page - F) * D + (E((this.current_page - 1) * G, this.shop_count) - E((F - 1) * G, this.shop_count)) + (E((this.current_page - 1) * A, this.promotion_count) - E((F - 1) * A, this.promotion_count))
        } else {
            if (F == this.current_page) {
                H = this.prev_start
            } else {
                H = 60 + (F - current_page - 1) * D - (E((F - 1) * G, shop_count) - E(current_page * G, shop_count)) - (E((F - 1) * A, promotion_count) - E(current_page * A, promotion_count))
            }
        }
    }
    this.base_url + "&page=" + F + "&s=" + H ;

};